package com.inspur.edp.formserver.vmmanager.vodtconsistencychecklistener;


import com.inspur.edp.bef.bizentity.bizentitydtevent.BizEntityDTEventListener;
import com.inspur.edp.bef.bizentity.dtconsistencycheck.entityeventargs.AbstractBeEntityArgs;
import com.inspur.edp.bef.bizentity.dtconsistencycheck.entityeventargs.RemovingEntityEventArgs;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.collection.GspFieldCollection;
import com.inspur.edp.cef.designtime.api.dtconsistencycheck.ConsistencyCheckEventMessage;
import com.inspur.edp.cef.designtime.api.element.GspElementObjectType;
import com.inspur.edp.das.commonmodel.IGspCommonElement;
import com.inspur.edp.das.commonmodel.IGspCommonObject;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.GspViewModelElement;
import com.inspur.edp.formserver.viewmodel.GspViewObject;
import com.inspur.edp.formserver.viewmodel.i18n.VMI8nResourceUtil;
import com.inspur.edp.formserver.viewmodel.i18n.names.VoResourceKeyNames;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.service.MetadataProjectService;
import com.inspur.edp.lcm.metadata.api.service.MetadataService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.util.ArrayList;
import java.util.List;

public class VoDTConsistencyCheckListener extends BizEntityDTEventListener {

    /**
     * 删除节点检查当前BE节点的VO关联和依赖信息
     *
     * @param args
     * @return
     */
    @Override
    public RemovingEntityEventArgs removingEntity(RemovingEntityEventArgs args) {
        return (RemovingEntityEventArgs) voConsistencyCheck(args);
    }

    /**
     * 对关联和依赖信息进行检查
     *
     * @param args
     * @return
     */
    protected AbstractBeEntityArgs voConsistencyCheck(AbstractBeEntityArgs args) {
        String returnMessage = getAssoAndDependencyInfos(args.getMetadataPath(), args.getBeId(),
                args.getBeEntityId());
        if (returnMessage == null || returnMessage.length() == 0) {
            return args;
        }
        ConsistencyCheckEventMessage message = new ConsistencyCheckEventMessage(true, returnMessage);
        args.addEventMessage(message);
        return args;
    }

    /**
     * 获取的关联信息
     *
     * @param metadataPath 元数据路径
     * @param beId         元数据ID
     * @param beNodeId     be节点ID
     * @return 关联当前BE的关联信息
     */
    protected String getAssoAndDependencyInfos(String metadataPath, String beId, String beNodeId) {
        MetadataService metadataService = SpringBeanUtils
                .getBean(com.inspur.edp.lcm.metadata.api.service.MetadataService.class);
        List<GspMetadata> gspMetadataList = metadataService
                .getMetadataListByRefedMetadataId(metadataPath, beId);
        StringBuilder strBuilder = new StringBuilder();
        for (GspMetadata gspMetadata : gspMetadataList) {
            if (!gspMetadata.getHeader().getType().equals("GSPViewModel")) {
                continue;
            }
            String packageName = null;
            GspViewModel viewModel = (GspViewModel) metadataService
                    .loadMetadata(gspMetadata.getHeader().getFileName(), gspMetadata.getRelativePath())
                    .getContent();
            ArrayList<IGspCommonObject> commonObjects = viewModel.getAllObjectList();
            for (IGspCommonObject viewObject : commonObjects) {
                //检查是否依赖的节点
                if (((GspViewObject) viewObject).getMapping() != null && ((GspViewObject) viewObject).getMapping().getTargetObjId().equals(beNodeId)) {
                    if (packageName == null) {
                        packageName = getProjectName(gspMetadata.getRelativePath());
                    }
                    strBuilder
                            .append(returnMessage(packageName, viewModel.getCode(), viewObject.getCode(), null));
                } else {
                    //检查是否是虚拟字段（关联）
                    ArrayList<IGspCommonElement> commonElements = viewObject.getAllElementList(false);
                    for (IGspCommonElement commonElement : commonElements) {
                        if (!getIsDependence((GspViewModelElement) commonElement, beNodeId)) {
                            continue;
                        }
                        if (packageName == null) {
                            packageName = getProjectName(gspMetadata.getRelativePath());
                        }
                        strBuilder.append(
                                returnMessage(packageName, gspMetadata.getHeader().getCode(), viewObject.getCode(),
                                        commonElement.getCode()));
                    }
                }
            }
        }
        if (strBuilder.toString() == null || strBuilder.toString().length() == 0) {
            return null;
        }
        return strBuilder.toString();
    }

    /**
     * 获取元数据包名
     *
     * @param metadataPath 元数据路径
     * @return 元数据包名
     */
    protected String getProjectName(String metadataPath) {
        MetadataProjectService projectService = SpringBeanUtils
                .getBean(com.inspur.edp.lcm.metadata.api.service.MetadataProjectService.class);
        return projectService.getMetadataProjInfo(metadataPath).getName();
    }

    protected boolean getIsDependence(GspViewModelElement vmElement, String beElementId) {
        //依赖
        if (vmElement.getMapping() != null && vmElement.getMapping().getTargetElementId().equals(beElementId)) {
            return true;
        }
        //虚拟字段关联
        if (vmElement.getObjectType() != GspElementObjectType.Association || !vmElement
                .getIsVirtual()) {
            return false;
        }
        if (vmElement.getChildAssociations().size() == 0) {
            return false;
        }
        GspFieldCollection fieldCollection = vmElement.getChildAssociations().get(0).getRefElementCollection();
        for (IGspCommonField field : fieldCollection) {
            if (field.getRefElementId().equals(beElementId))
                return true;
        }
        return false;
    }

    /**
     * 拼接返回值信息
     */
    protected String returnMessage(String packageName, String voCode, String nodeCode,
                                   String fieldCode) {
        if (fieldCode == null) {
            return VMI8nResourceUtil.getMessage(VoResourceKeyNames.VO_OBJECT_CONSISTENCY_CHECK_PREFIX,
                    packageName, voCode, nodeCode);
        } else {
            return VMI8nResourceUtil.getMessage(VoResourceKeyNames.VO_ELEMENT_RELY_OBJECT_CONSISTENCY_CHECK_PREFIX,
                    packageName, voCode, nodeCode, fieldCode);
        }
    }
}
